import open3d as o3d

def render_from_viewpoint(mesh_path, camera_position, look_at):
    width, height = 640, 480

    # 创建渲染器
    renderer = o3d.visualization.rendering.OffscreenRenderer(width, height)

    # 设置场景背景和材质
    renderer.scene.set_background([1, 1, 1, 1])
    material = o3d.visualization.rendering.MaterialRecord()
    material.shader = "defaultLit"

    # 读取网格
    mesh = o3d.io.read_triangle_mesh(mesh_path)
    # 计算顶点的法线(normal)
    mesh.compute_vertex_normals()
    renderer.scene.add_geometry("mesh", mesh, material)

    # 设置摄像头视角
    center = look_at
    eye = camera_position
    up = [0, 1, 0]
    renderer.scene.camera.look_at(center, eye, up)

    # 渲染图像并保存
    img = renderer.render_to_image()
    o3d.io.write_image("rendered_open3d.png", img)
    print("✅ 渲染成功，图像已保存：rendered_open3d.png")

# 示例：调用函数
mesh_path = "/data/workspace/3D/room_ws/dense_291_individual/meshed-poisson.ply"
camera_position = [0.0, 0.0, 2.0]  # 视角位置
look_at = [0.0, 0.0, 0.0]         # 看向原点
render_from_viewpoint(mesh_path, camera_position, look_at)
